package com.hub.realtime.framework.service;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hub.realtime.common.core.domain.entity.SysRole;
import com.hub.realtime.common.core.domain.entity.SysUser;
import com.hub.realtime.common.core.domain.model.LoginUser;
import com.hub.realtime.common.dto.input.BasePageQuery;
import com.hub.realtime.common.utils.ServletUtils;
import com.hub.realtime.framework.web.service.TokenService;
import com.hub.realtime.system.service.ISysUserService;
import com.streamxhub.streamx.common.util.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;


public abstract class ServiceBase<M extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T>, T> extends ServiceImpl<M, T> {


    @Autowired
    TokenService tokenService;


    @Autowired
    ISysUserService userService;

    protected ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors() * 2,
            200,
            60L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1024),
            ThreadUtils.threadFactory("realtime-flink-executor"),
            new ThreadPoolExecutor.AbortPolicy()
    );


    /**
     * 获取当前登录的用户
     *
     * @return
     */
    public LoginUser getLoginUser() {
        HttpServletRequest request = ServletUtils.getRequest();
        return tokenService.getLoginUser(request);
    }


    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    public SysUser getCurrentUser(Long userId) {
        if (userId == null) {
            userId = getLoginUser().getUserId();
        }
        return userService.selectUserById(userId);
    }

    /**
     * 获取用户权限
     *
     * @param userId
     * @return
     */
    public List<SysRole> getUserRoles(Long userId) {
        if (userId == null) {
            userId = getLoginUser().getUserId();
        }
        SysUser sysUser = userService.selectUserById(userId);
        return sysUser.getRoles();
    }

    public int delByIds(Long[] ids) {
        List<Long> listIds = Arrays.stream(ids).collect(Collectors.toList());
        return baseMapper.deleteBatchIds(listIds);
    }

    /**
     * 主要判断当前用户是否超级用户
     * @param eqFunction
     * @param orderbyFunction
     * @return
     */
    protected LambdaQueryWrapper<T> createCommonWrapper(SFunction<T,?> eqFunction,SFunction<T,?> orderbyFunction)
    {
        LoginUser loginUser = getLoginUser();
        List<SysRole> userRoles = getUserRoles(null);
        LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
        boolean isAdmin = false;
        if (userRoles != null && userRoles.size() > 0) {
            List<SysRole> admins = userRoles.stream().filter(role -> role.getRoleKey().equalsIgnoreCase("admin")).collect(Collectors.toList());
            //表示当前用户是超级用户，可以查询全部
            if (!admins.isEmpty()) {
                isAdmin = true;
            }
        }
        if (!isAdmin) {
            wrapper.eq(eqFunction,loginUser.getUserId())
                    .orderByDesc(orderbyFunction);
        }
        return wrapper;
    }

    /**
     * 获取分页数据
     * @param param
     * @param wrapper
     * @return
     */
    protected  Page<T>getPageList(BasePageQuery param, Wrapper<T>wrapper)
    {
        Page<T> page = new Page<>(param.getPageNum(), param.getPageSize());
       return  baseMapper.selectPage(page, wrapper);
    }



}
